<?php
require "./lib/browser.php";

$config = require('./lib/config.php');
$browser = Browser::detect();
$qqFlag = $config['QQBROWSER_FLAG'];  // QQ浏览器拦截开关
$redirectBrowsers = ["qqbrowser","mqqbrowser", "ucbrowser", "vivobrowser"];
$mobileBrowsers = ["wechatbrowser", "mqqInternalBrowser"];
$iCode = isset($_GET["i_code"]) && $_GET["i_code"] != ""  ? "?i_code=" . trim($_GET["i_code"]) : "";
$rCode = isset($_GET["r_code"]) && $_GET["r_code"] != ""  ? "?r_code=" . trim($_GET["r_code"]) : "";
$isAppUpdate = isset($_GET["isAppUpdate"]) && $_GET["isAppUpdate"] != "" 
    ? (strpos($_SERVER['REQUEST_URI'], '?') === false ? "?isAppUpdate=" . trim($_GET["isAppUpdate"]) : "&isAppUpdate=" . trim($_GET["isAppUpdate"])) 
    : "";

     // 检查请求的 URI 是否已经包含 ?isAppUpdate
if (strpos($_SERVER['REQUEST_URI'], '?isAppUpdate') !== false) {
  parse_str(parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY), $queryParams);
  if (isset($queryParams['isAppUpdate'])) {
      $isAppUpdate = "?isAppUpdate=" . trim($queryParams['isAppUpdate']); // 使用现有值
  }
} elseif ($isAppUpdate === "?isAppUpdate=") {
  $isAppUpdate = "";
}


if (in_array($browser["name"], $redirectBrowsers)) {
  if( $browser["platform"] == "iphone" && ($browser["name"] == "ucbrowser" || $browser["name"] == "mqqbrowser")){
    if ($browser["name"] == "mqqbrowser") {
      if ($qqFlag == '' || $qqFlag == '0') {
        header("Location:./download.html" . $iCode . $rCode . $isAppUpdate);
      } else {
        header("Location:./download.html" . $iCode . $rCode . $isAppUpdate);
      }
    } else {
        header("Location:./download.html" . $iCode . $rCode . $isAppUpdate);
    }
  } elseif ($browser["platform"] == "android" && $browser["name"] == "mqqbrowser"){
    if ($browser["name"] == "mqqbrowser") {
      if ($qqFlag == '' || $qqFlag == '0') {
        header("Location:./download.html" . $iCode . $rCode . $isAppUpdate);
      } else {
        header("Location:./download.html" . $iCode . $rCode . $isAppUpdate);
      }
    } else {
        header("Location:./download.html" . $iCode . $rCode . $isAppUpdate);
    }
  } elseif ($browser["platform"] == "android" && $browser["name"] == "vivobrowser" )  {
    header("Location:./download.html" . $iCode . $rCode . $isAppUpdate);
  } else {
    header("Location:./download.html" . $iCode . $rCode . $isAppUpdate  );
  }
} elseif (in_array($browser["name"], $mobileBrowsers)) {
    header("Location:./download.html" . $iCode . $rCode . $isAppUpdate);
} else {
  header("Location:./download.html" . $iCode . $rCode . $isAppUpdate);
}

return;